#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import jsonify, request
from flask_restful import Resource
from utility.odoo_manager import OdooManager  # 操作odoo的单例
from utility.error_code import error_code  # 异常代码
from utility.message_manager import MessageBusManager
from event import event_type
from command import command
import logging
from utility import tools

FORMAT = "%(asctime)s %(thread)d %(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT)


class AskInquiryPartumAddAPI(Resource):
    """
    常规产后42天问询
    :request: post
    :param archivesId: 档案ID
    :param type: 类型 2-常规体检问询 7-产后42天体检问询
    :param ybzzYjdzhx: 夜间端坐呼吸
    :param ybzzKs: 咳嗽
    :param ybzzEx: 恶心
    :param ybzzFl: 乏力
    :param ybzzSfbbs: 上腹部不适
    :param ybzzNxgnyc: 凝血功能异常
    :param ybzzOt: 呕吐
    :param ybzzFg: 发绀
    :param ybzzXs: 消瘦
    :param ybzzXxbjs: 血小板减少
    :param ybzzGzmxyc: 肝脏酶学异常
    :param ybzzCh: 出汗
    :param ybzzYt: 眼突
    :param ybzzDxt: 低血糖
    :param ybzzSszc: 双手震颤
    :param ybzzXm: 胸闷
    :param ybzzFz: 浮肿
    :param ybzzHd: 黄疸
    :param ybzzXj: 心悸
    :returns: json string
    """
    def post(self):
        try:
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            # 参数校验
            req_params = ['archivesId']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            # 创建初检问询档案
            data_={
                #'inspection_log_id': '',
                'archives_id': params.get('archivesId'),
                'type': params.get('type'),
                'ybzz_yjdzhx': params.get('ybzzYjdzhx'),
                'ybzz_ks': params.get('ybzzKs'),
                'ybzz_ex': params.get('ybzzEx'),
                'ybzz_fl': params.get('ybzzFl'),
                'ybzz_sfbbs': params.get('ybzzSfbbs'),
                'ybzz_nxgnyc': params.get('ybzzNxgnyc'),
                'ybzz_ot': params.get('ybzzOt'),
                'ybzz_fg': params.get('ybzzFg'),
                'ybzz_xs': params.get('ybzzXs'),
                'ybzz_xxbjs': params.get('ybzzXxbjs'),
                'ybzz_gzmxyc': params.get('ybzzGzmxyc'),
                'ybzz_ch': params.get('ybzzCh'),
                'ybzz_yt': params.get('ybzzYt'),
                'ybzz_dxt': params.get('ybzzDxt'),
                'ybzz_sszc': params.get('ybzzSszc'),
                'ybzz_xm': params.get('ybzzXm'),
                'ybzz_fz': params.get('ybzzFz'),
                'ybzz_hd': params.get('ybzzHd'),
                'ybzz_xj': params.get('ybzzXj'),
                'hospital_id': 1
            }
            data_ = odoo.env['inspection.inquiries'].create(data_)
            create_event = event_type.OperationLogEvent('常规产后42天问询', '档案id:{}'.format(params.get('archivesId')))
            message_bus = MessageBusManager().get_message_bus()
            message_bus.handle(create_event)  # 发布事件
            # 创建检查记录
            check_data_ = {
                'archives_id': params.get('archivesId'),
                'type': params.get('type'),
                'wx_id': data_,
                'state': 0
            }
            check_data_ = odoo.env['inspection.log'].create(check_data_)
            create_event = event_type.OperationLogEvent('创建检查记录', '档案id:{},cjda_id{}'.format(params.get('archivesId'),data_))
            message_bus = MessageBusManager().get_message_bus()
            message_bus.handle(create_event)  # 发布事件
            # 更新实验室及辅助检查logid
            u_data_ = {'inspection_log_id': check_data_}
            data_u = odoo.env['inspection.inquiries'].write(data_,u_data_)
            create_event = event_type.OperationLogEvent('更新实验室及辅助检查logid', '档案id:{}'.format(params.get('archivesId')))
            message_bus = MessageBusManager().get_message_bus()
            message_bus.handle(create_event)  # 发布事件
            return jsonify({'code': 0, 'msg': 'success', 'data': {'logId': check_data_,'id': data_}, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class AskInquiryPartumUpdateAPI(Resource):
    """
    更新常规产后42天问询
    :request: put
    :param archivesId: 档案ID
    :param logid: 检查表ID
    :param ybzzYjdzhx: 夜间端坐呼吸
    :param ybzzKs: 咳嗽
    :param ybzzEx: 恶心
    :param ybzzFl: 乏力
    :param ybzzSfbbs: 上腹部不适
    :param ybzzNxgnyc: 凝血功能异常
    :param ybzzOt: 呕吐
    :param ybzzFg: 发绀
    :param ybzzXs: 消瘦
    :param ybzzXxbjs: 血小板减少
    :param ybzzGzmxyc: 肝脏酶学异常
    :param ybzzCh: 出汗
    :param ybzzYt: 眼突
    :param ybzzDxt: 低血糖
    :param ybzzSszc: 双手震颤
    :param ybzzXm: 胸闷
    :param ybzzFz: 浮肿
    :param ybzzHd: 黄疸
    :param ybzzXj: 心悸
    :returns: json string
    """
    def put(self):
        try:
            odoo = OdooManager().get_instance()
            params = request.json
            # 参数校验
            req_params = ['archivesId','logId']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            # 更新常规产后42天问询
            data_={
                #'inspection_log_id': '',
                'archives_id': params.get('archivesId'),
                'type': params.get('type'),
                'ybzz_yjdzhx': params.get('ybzzYjdzhx'),
                'ybzz_ks': params.get('ybzzKs'),
                'ybzz_ex': params.get('ybzzEx'),
                'ybzz_fl': params.get('ybzzFl'),
                'ybzz_sfbbs': params.get('ybzzSfbbs'),
                'ybzz_nxgnyc': params.get('ybzzNxgnyc'),
                'ybzz_ot': params.get('ybzzOt'),
                'ybzz_fg': params.get('ybzzFg'),
                'ybzz_xs': params.get('ybzzXs'),
                'ybzz_xxbjs': params.get('ybzzXxbjs'),
                'ybzz_gzmxyc': params.get('ybzzGzmxyc'),
                'ybzz_ch': params.get('ybzzCh'),
                'ybzz_yt': params.get('ybzzYt'),
                'ybzz_dxt': params.get('ybzzDxt'),
                'ybzz_sszc': params.get('ybzzSszc'),
                'ybzz_xm': params.get('ybzzXm'),
                'ybzz_fz': params.get('ybzzFz'),
                'ybzz_hd': params.get('ybzzHd'),
                'ybzz_xj': params.get('ybzzXj')
            }
            query_ = [
                ('archives_id', '=', int(params.get('archivesId'))),
                ('inspection_log_id', '=', int(params.get('logId')))
            ]
            inspection_inquiries = odoo.env['inspection.inquiries'].search(query_)
            if not inspection_inquiries:
                return jsonify({'code': 40005, 'msg': error_code[40005]})  
            data_ = odoo.env['inspection.inquiries'].write(inspection_inquiries,data_)
            create_event = event_type.OperationLogEvent('更新常规产后42天问询', '档案id:{}'.format(params.get('archivesId')))
            message_bus = MessageBusManager().get_message_bus()
            message_bus.handle(create_event)  # 发布事件
            return jsonify({'code': 0, 'msg': 'success', 'data': {'logId': params.get('logId'),'id': inspection_inquiries[0]}, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class AskInquiryPartumQueryHisAPI(Resource):
    """
    常规及产后42天问询回显+历史
    :request: post
    :param archivesId: 档案ID
    :param logId: logId
    :param type: 类型 NULL 不区分 0 在途 1完成
    :returns: json string
    """
    def post(self):
        try:
            #  获取常规及产后42天问询回显+历史
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            query_ = []
            params = request.values
            if  params.get('archivesId'):
                query_.append(('archives_id', '=', int(params.get('archivesId')))) 
            if  params.get('logId'):
                query_.append(('inspection_log_id', '=', int(params.get('logId'))))  
            if  params.get('type'):
                c_query_ = [
                    ('state', '=', int(params.get('type'))),
                    ('type', '=', 1),
                ]
                inspection_log = odoo.env['inspection.log'].search_read(c_query_,['pid'])
                if inspection_log:
                    query_.append(('id', 'in', list(set([log_['pid'] for log_ in inspection_log]))))
            inspection_inquiries = odoo.env['inspection.inquiries'].search_read(query_)
            if inspection_inquiries:
                inspection_inquiries = inspection_inquiries[0]
                print (inspection_inquiries)
                data_ = {
                    'ybzz': {
                        'ybzzYjdzhx': inspection_inquiries['ybzz_yjdzhx'],
                        'ybzzKs': inspection_inquiries['ybzz_ks'],
                        'ybzzEx': inspection_inquiries['ybzz_ex'],
                        'ybzzFl': inspection_inquiries['ybzz_fl'],
                        'ybzzSfbbs': inspection_inquiries['ybzz_sfbbs'],
                        'ybzzNxgnyc': inspection_inquiries['ybzz_nxgnyc'],
                        'ybzzOt': inspection_inquiries['ybzz_ot'],
                        'ybzzFg': inspection_inquiries['ybzz_fg'],
                        'ybzzXs': inspection_inquiries['ybzz_xs'],
                        'ybzzXxbjs': inspection_inquiries['ybzz_xxbjs'],
                        'ybzzGzmxyc': inspection_inquiries['ybzz_gzmxyc'],
                        'ybzzCh': inspection_inquiries['ybzz_ch'],
                        'ybzzYt': inspection_inquiries['ybzz_yt'],
                        'ybzzDxt': inspection_inquiries['ybzz_dxt'],
                        'ybzzSszc': inspection_inquiries['ybzz_sszc'],
                        'ybzzXm': inspection_inquiries['ybzz_xm'],
                        'ybzzFz': inspection_inquiries['ybzz_fz'],
                        'ybzzHd': inspection_inquiries['ybzz_hd'],
                        'ybzzXj': inspection_inquiries['ybzz_xj']
                    },
                    'jbxx': {
                        'createTime': inspection_inquiries['create_date'],
                        'cjrCode': inspection_inquiries['create_uid'][0] if inspection_inquiries['create_uid'] else '',
                        'cjrName': inspection_inquiries['create_uid'][1] if inspection_inquiries['create_uid'] else '',
                        'cjjgCode': inspection_inquiries['hospital_id'][0] if inspection_inquiries['hospital_id'] else '',
                        'cjjgName': inspection_inquiries['hospital_id'][1] if inspection_inquiries['hospital_id'] else '',
                        'lastUpdateTime': inspection_inquiries['__last_update'],
                        'lastUpdateBy': inspection_inquiries['write_uid'][1] if inspection_inquiries['write_uid'] else '',
                        'lastUpdateJgCode': inspection_inquiries['hospital_id'][0] if inspection_inquiries['hospital_id'] else '',
                        'lastUpdateJgName': inspection_inquiries['hospital_id'][1] if inspection_inquiries['hospital_id'] else ''
                    }
                }
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

